package com.dycong.common.IO.netty.Packet_Splicing;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * Created by dycong on 2017/3/13.
 */
public class EchoClient {

    private final String host;
    private final int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {


                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline()
                                    //todo 行解码器，以换行符分割
                                    .addLast(new LineBasedFrameDecoder(2048))
                                    //todo 定长数据帧的解码器
                                    .addLast(new FixedLengthFrameDecoder(20))
                                    //todo 分隔符解码器  客户端发送了2次req字节，每个req中有10个“$$__”，这样就是第11次切割的时候其实发送了粘包，第一个req中末尾部分和第二次的头部粘在了一起，作为第11部分的内容而最后一部分的内容因为没有"$$__"切割，所以没有打印在控制台上~
                                    .addLast(new DelimiterBasedFrameDecoder(2048, Unpooled.copiedBuffer("$$_".getBytes())))
                                    .addLast(new StringEncoder())
                                    .addLast(new StringDecoder())
                                    .addLast(clientHandler);
                        }
                    });
            ChannelFuture f =  b.connect(new InetSocketAddress(host, port)).sync();

            f.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully().sync();
        }
    }

    static EchoClientHandler clientHandler = new EchoClientHandler();

    public static void main(String[] args) throws Exception {


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    new EchoClient("localhost", 9090).start();
                }catch (Exception e){

                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (clientHandler.sendMsg(scanner.nextLine()));
         ;
    }

    /*
    todo StringEncoder:
    todo String(CharSequence)->ByteBuf的encoder
    todo 也可自定义其他转换例如;Integer->ByteBuf,继承MessageToMessageEncoder<T>,MessageToMessageDecoder<I>实现方法
    todo     protected abstract void encode(ChannelHandlerContext ctx, I msg, List<Object> out) throws Exception;
     @Override
    protected void encode(ChannelHandlerContext ctx, CharSequence msg, List<Object> out) throws Exception {
        if (msg.length() == 0) {
            return;
        }

        out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(msg), charset));
    }


    StringDecoder:
    ByteBuf->String(CharSequence)的encoder
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        out.add(msg.toString(charset));
    }

     */
}
